﻿using BCCommon;
using BCData.TMS.Agent.AgentAreaRecord;
using BCData.TMS.MoveHouseConfig.MoveHouseConfig;
using BCData.TMS.MoveHouseConfig.MoveHouseSpecificationConfig;
using BCData.TMS.MoveHouseConfig.MoveHouseSpecificationServiceConfig;
using BCData.TMS.MoveHouseConfig.MoveHouseSpecificationServiceConfigOverWrite;
using BCDto.Sim.Admin.Admin;
using BCDto.TMS.MoveHouseConfig.MoveHouseSpecificationConfig;
using BCDto.TMS.MoveHouseConfig.MoveHouseSpecificationServiceConfig;
using BCDto.TMS.MoveHouseConfig.MoveHouseSpecificationServiceConfigOverWrite;
using BCEntity.Common.EntityNameConst;
using BCEntity.TMS.MoveHouseConfig.MoveHouseSpecificationServiceConfigOverWrite;
using BCService.Common.Area;
using BCService.TMS.Agent.AgentAreaRecord;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace BCService.TMS.MoveHouseConfig.MoveHouseSpecificationServiceConfig
{
    public class MoveHouseSpecificationServiceConfigService : IMoveHouseSpecificationServiceConfigService
    {
        private readonly IDatabaseContext databaseContext;
        private readonly IMoveHouseSpecificationConfigData moveHouseSpecificationConfigData;
        private readonly IMoveHouseConfigData moveHouseConfigData;
        private readonly IMoveHouseSpecificationServiceConfigData moveHouseSpecificationServiceConfigData;
        private readonly IMoveHouseSpecificationServiceConfigOverWriteData moveHouseSpecificationServiceConfigOverWriteData;
        private readonly IRedisService redisService;
        private readonly IZoneService zoneService;
        private readonly IAgentAreaRecordData agentAreaRecordData;
        private readonly IAgentAreaRecordService agentAreaRecordService;
        private readonly string key = string.Format("{0}", EntityNameConst.MoveHouseSpecificationServiceConfigEntity);
        private readonly string keyOverWrite = string.Format("{0}", EntityNameConst.MoveHouseSpecificationServiceConfigOverWriteEntity);
        private readonly string keyView = string.Format("{0}", EntityNameConst.MoveHouseSpecificationServiceConfigViewEntity);
        public MoveHouseSpecificationServiceConfigService(IDatabaseContext databaseContext,
            IMoveHouseSpecificationConfigData moveHouseSpecificationConfigData,
            IMoveHouseConfigData moveHouseConfigData,
            IMoveHouseSpecificationServiceConfigData moveHouseSpecificationServiceConfigData,
            IMoveHouseSpecificationServiceConfigOverWriteData moveHouseSpecificationServiceConfigOverWriteData,
            IRedisService redisService,
            IZoneService zoneService,
            IAgentAreaRecordData agentAreaRecordData,
            IAgentAreaRecordService agentAreaRecordService)
        {
            this.databaseContext = databaseContext;
            this.moveHouseSpecificationConfigData = moveHouseSpecificationConfigData;
            this.moveHouseConfigData = moveHouseConfigData;
            this.moveHouseSpecificationServiceConfigData = moveHouseSpecificationServiceConfigData;
            this.moveHouseSpecificationServiceConfigOverWriteData = moveHouseSpecificationServiceConfigOverWriteData;
            this.redisService = redisService;
            this.zoneService = zoneService;
            this.agentAreaRecordData = agentAreaRecordData;
            this.agentAreaRecordService = agentAreaRecordService;
        }
        public PageableList<MoveHouseSpecificationServiceConfigOverWriteViewDto> GetAllAgentPriceList(AdminDto admin, string countyCode, bool? enabled,
            int pageIndex, int pageSize)
        {
            if (admin.AgentRecord == null)
            {
                throw new ArgumentException(" 用户验证失败,错误操作 ");
            }
            string provinceCode = string.Empty;
            string cityCode = string.Empty;
            if (!string.IsNullOrWhiteSpace(countyCode))
            {
                var zoneEntity = zoneService.GetFromZoneEntity(countyCode);
                if (zoneEntity == null || zoneEntity.provinceEntity == null || zoneEntity.cityEntity == null || zoneEntity.countyEntity == null)
                {
                    throw new ArgumentException("此区域信息不正确!");
                }
                var agentAreaRecordEntity = agentAreaRecordService.GetLastLevelByCode(zoneEntity.countyEntity.CountyCode);
                if (agentAreaRecordEntity==null)
                {
                    throw new ArgumentException(" 当前地区未开通,错误数据 ");
                }
                if (agentAreaRecordEntity.AgentAreaRecordId == admin.AgentRecord.AgentRecordId)
                {
                    throw new ArgumentException(" 您不是当前地区的代理商,不可开通服务 ");
                }
                provinceCode = zoneEntity.provinceEntity.ProvinceCode;
                cityCode = zoneEntity.cityEntity.CityCode;
                countyCode = zoneEntity.countyEntity.CountyCode;
            }

            string cacheKey = this.redisService.GetKey(keyView, enabled, pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var (list, count) = moveHouseSpecificationServiceConfigData.GetAllAgentPriceList(admin.AgentRecord.AgentRecordId,
                    provinceCode, cityCode, countyCode,
                    enabled, pageIndex, pageSize).Result;
                return new PageableList<MoveHouseSpecificationServiceConfigOverWriteViewDto>
                {
                    Items = list.As<IEnumerable<MoveHouseSpecificationServiceConfigOverWriteViewDto>>(),
                    Count = count
                };
            }, TimeSpan.FromDays(1));
            return result;
        }

        public PageableList<MoveHouseSpecificationServiceConfigViewDto> GetAllPriceQuery(AdminDto admin, bool? enabled,
            int pageIndex, int pageSize)
        {
            string cacheKey = this.redisService.GetKey(keyView, enabled, pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var (list, count) = moveHouseSpecificationServiceConfigData.GetAllPriceQuery(enabled, pageIndex, pageSize).Result;
                return new PageableList<MoveHouseSpecificationServiceConfigViewDto>
                {
                    Items = list.As<IEnumerable<MoveHouseSpecificationServiceConfigViewDto>>(),
                    Count = count
                };
            }, TimeSpan.FromDays(1));
            return result;
        }

        public bool Create(IEnumerable<long> moveHouseSpecificationServiceConfigIdList, string countyCode, AdminDto admin)
        {
            var houseSpecificationServiceConfigIdList = moveHouseSpecificationServiceConfigIdList.ToList();
            if (!houseSpecificationServiceConfigIdList.Any())
            {
                throw new ArgumentException(" 请选择服务 ");
            }
            if (admin.AgentRecord == null)
            {
                throw new ArgumentException(" 用户验证失败,错误操作 ");
            }
            long agentRecordId = admin.AgentRecord.AgentRecordId;
            var zoneEntity = zoneService.GetFromZoneEntity(countyCode);
            if (zoneEntity == null || zoneEntity.provinceEntity == null || zoneEntity.cityEntity == null || zoneEntity.countyEntity == null)
            {
                throw new ArgumentException("此区域信息不正确!");
            }
            var agentAreaRecordEntity = agentAreaRecordService.GetLastLevelByCode(zoneEntity.countyEntity.CountyCode);
            if (agentAreaRecordEntity == null)
            {
                throw new ArgumentException(" 当前地区未开通,错误数据 ");
            }
            if (agentAreaRecordEntity.AgentRecordId != admin.AgentRecord.AgentRecordId)
            {
                throw new ArgumentException(" 当前选择的地区中存在 您未管辖的地区 (" + zoneEntity.countyEntity.CountyName + ") ,请重新选择 ");
            }
            foreach (var item in houseSpecificationServiceConfigIdList)
            {
                var moveHouseSpecificationServiceConfig = moveHouseSpecificationServiceConfigData.GetSingle(item).Result;
                if (moveHouseSpecificationServiceConfig == null)
                {
                    throw new ArgumentException(" 当前搬家服务不存在,不可开通 ");
                }
                if (!moveHouseSpecificationServiceConfig.Enabled)
                {
                    throw new ArgumentException(" 当前搬家服务被禁用,不可开通 ");
                }
                var isExist = moveHouseSpecificationServiceConfigOverWriteData.GetEntityByConfigId(item, agentRecordId, zoneEntity.countyEntity.CountyCode).Result != null;
                if (isExist)
                {
                    continue;
                }
                var overWrite = new MoveHouseSpecificationServiceConfigOverWriteEntity()
                {
                    MoveHouseSpecificationServiceConfigId = item,
                    MoveHouseConfigId = moveHouseSpecificationServiceConfig.MoveHouseConfigId,
                    MoveHouseSpecificationConfigId = moveHouseSpecificationServiceConfig.MoveHouseSpecificationConfigId,
                    SpecificationName = moveHouseSpecificationServiceConfig.SpecificationName,
                    SpecificationServiceConfigId = moveHouseSpecificationServiceConfig.SpecificationServiceConfigId,
                    SpecificationServiceName = moveHouseSpecificationServiceConfig.SpecificationServiceName,
                    Price = moveHouseSpecificationServiceConfig.Price,
                    ProvinceCode = zoneEntity.provinceEntity.ProvinceCode,
                    CityCode = zoneEntity.cityEntity.CityCode,
                    CountyCode = zoneEntity.countyEntity.CountyCode,
                    AgentRecordId = agentRecordId,
                    Remark = moveHouseSpecificationServiceConfig.Remark,
                    Enabled = moveHouseSpecificationServiceConfig.Enabled,
                    CreateAdminId = admin.AdminId,
                    CreateAdminName = admin.FullName,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    EditAdminId = admin.AdminId,
                    EditAdminName = admin.FullName,
                };
                var result = moveHouseSpecificationServiceConfigOverWriteData.InsertAsync(overWrite).GetAwaiter().GetResult();
                if (result != null) continue;
                var moveHouseConfigEntity = moveHouseConfigData.GetSingle(result.MoveHouseConfigId).Result;
                throw new ArgumentException(moveHouseConfigEntity.MoveHouseConfigName + "分类下的" + moveHouseSpecificationServiceConfig.SpecificationName + " 规格下的" + moveHouseSpecificationServiceConfig.SpecificationServiceName + "服务 开通失败");
            }
            this.redisService.DeleteMultipleKey(keyOverWrite, false);
            return true;
        }

        public MoveHouseSpecificationServiceConfigDto GetById(long moveHouseSpecificationServiceConfigId)
        {
            string cacheKey = this.redisService.GetKey(key,moveHouseSpecificationServiceConfigId);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var list = moveHouseSpecificationServiceConfigData.GetSingle(moveHouseSpecificationServiceConfigId).Result.As<MoveHouseSpecificationServiceConfigDto>();
                return list;
            }, TimeSpan.FromDays(1));
            return result;
        }


        public IEnumerable<MoveHouseSpecificationConfigClientDto> GetSpecification(long moveHouseConfigId, string countyCode)
        {
            if (string.IsNullOrWhiteSpace(countyCode))
            {
                throw new ArgumentException("请选择要设置业务的行政区域!");
            }
            var zoneEntity = this.zoneService.GetFromZoneEntity(countyCode);
            if (zoneEntity == null || zoneEntity.provinceEntity == null || zoneEntity.cityEntity == null || zoneEntity.countyEntity == null)
            {
                throw new ArgumentException("此区域信息不正确!");
            }
            var moveHouseConfigEntity = this.moveHouseConfigData.GetSingle(moveHouseConfigId).Result;
            if (moveHouseConfigEntity == null)
            {
                throw new ArgumentException(" 获取搬家设置信息失败 ");
            }
            string cacheKey = this.redisService.GetKey(key, moveHouseConfigId, true);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var moveHouseSpecificationConfig = moveHouseSpecificationConfigData.GetList(moveHouseConfigId, true).Result;
                var list = new List<MoveHouseSpecificationConfigClientDto>();
                foreach (var item in moveHouseSpecificationConfig)
                {
                    var serviceClient = new List<MoveHouseSpecificationServiceConfigClientDto>();
                    var serviceResults = moveHouseSpecificationServiceConfigData.GetList(item.MoveHouseSpecificationConfigId, true).Result;
                    foreach (var itemService in serviceResults)
                    {
                        var resultServiceItem = new MoveHouseSpecificationServiceConfigClientDto()
                        {
                            SpecificationServiceConfigId = itemService.SpecificationServiceConfigId,
                            SpecificationServiceName = itemService.SpecificationServiceName,
                        };
                        serviceClient.Add(resultServiceItem);
                    }
                    var resultItem = new MoveHouseSpecificationConfigClientDto()
                    {
                        MoveHouseConfigId = moveHouseConfigEntity.MoveHouseConfigId,
                        MoveHouseConfigName = moveHouseConfigEntity.MoveHouseConfigName,
                        MoveHouseSpecificationConfigId = item.MoveHouseSpecificationConfigId,
                        SpecificationName = item.SpecificationName,
                        MoveHouseServiceConfigClients = serviceClient,
                    };
                    list.Add(resultItem);
                }
                return list;
            }, TimeSpan.FromDays(1));
            return result;
        }

        public IEnumerable<MoveHouseSpecificationServiceConfigPriceClientDto> GetPrice(long moveHouseConfigId,long? agentRecordId, string countyCode)
        {
            if (string.IsNullOrWhiteSpace(countyCode))
            {
                throw new ArgumentException("请选择要设置业务的行政区域!");
            }
            if (!agentRecordId.HasValue)
            {
                throw new ArgumentException("代理商验证失败,错误操作!");
            }
            var zoneEntity = this.zoneService.GetFromZoneEntity(countyCode);
            if (zoneEntity == null || zoneEntity.provinceEntity == null || zoneEntity.cityEntity == null || zoneEntity.countyEntity == null)
            {
                throw new ArgumentException("此区域信息不正确!");
            }
            var moveHouseConfigEntity = this.moveHouseConfigData.GetSingle(moveHouseConfigId).Result;
            if (moveHouseConfigEntity == null)
            {
                throw new ArgumentException(" 获取搬家设置信息失败 ");
            }
            string cacheKey = this.redisService.GetKey(key, moveHouseConfigId, true);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var moveHouseSpecificationServiceConfigs = moveHouseSpecificationServiceConfigData.GetListByMoveHouseConfigId(moveHouseConfigId, true).Result;
                var moveHouseSpecificationServiceConfigOverWrites = moveHouseSpecificationServiceConfigOverWriteData.GetListByMoveHouseConfigId(moveHouseConfigId,
                    zoneEntity.provinceEntity.ProvinceCode,zoneEntity.cityEntity.CityCode, zoneEntity.countyEntity.CountyCode, agentRecordId.Value, true).Result;
                var list = new List<MoveHouseSpecificationServiceConfigPriceClientDto>();
                foreach (var item in moveHouseSpecificationServiceConfigs)
                {
                    var resultItem = new MoveHouseSpecificationServiceConfigPriceClientDto()
                    {
                        MoveHouseSpecificationServiceConfigId = item.MoveHouseSpecificationServiceConfigId,
                        MoveHouseConfigId = moveHouseConfigEntity.MoveHouseConfigId,
                        MoveHouseConfigName = moveHouseConfigEntity.MoveHouseConfigName,
                        MoveHouseSpecificationConfigId = item.MoveHouseSpecificationConfigId,
                        SpecificationName = item.SpecificationName,
                        SpecificationServiceConfigId = item.SpecificationServiceConfigId,
                        SpecificationServiceName = item.SpecificationServiceName,
                        Price = item.Price,
                    };
                    var overWrite = moveHouseSpecificationServiceConfigOverWrites.FirstOrDefault(p =>
                        p.MoveHouseSpecificationServiceConfigId == item.MoveHouseSpecificationServiceConfigId);
                    if (overWrite?.Price != null)
                    {
                        resultItem.MoveHouseSpecificationServiceConfigOverWriteId =
                            overWrite.MoveHouseSpecificationServiceConfigOverWriteId;
                        resultItem.Price = overWrite.Price.Value;
                    }

                    list.Add(resultItem);
                }

                return list;
            }, TimeSpan.FromDays(1));
            return result;
        }

        public bool Delete(long moveHouseSpecificationServiceConfigId, AdminDto admin)
        {
            if (admin.CompanyId != 1)
            {
                throw new ArgumentException(" 用户认证失败,错误操作 ");
            }
            var entity = moveHouseSpecificationServiceConfigData.GetSingle(moveHouseSpecificationServiceConfigId).Result;
            if (entity == null)
            {
                throw new ArgumentException(" 获取规格服务信息失败,请检查数据 ");
            }
            var overWrite = moveHouseSpecificationServiceConfigOverWriteData.GetEntityByConfigId(moveHouseSpecificationServiceConfigId).Result;
            if (overWrite != null)
            {
                throw new ArgumentException(" 当前规格已被代理商重写,不可删除 ");
            }
            var result = moveHouseSpecificationServiceConfigData.DeleteAsync(moveHouseSpecificationServiceConfigId).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
            return result > 0;
        }

        public bool UpdatePrice(long moveHouseSpecificationServiceConfigId, decimal price, AdminDto admin)
        {
            if (admin.CompanyId != 1)
            {
                throw new ArgumentException(" 用户认证失败,错误操作 ");
            }
            var entity = moveHouseSpecificationServiceConfigData.GetSingle(moveHouseSpecificationServiceConfigId).Result;
            if (entity == null)
            {
                throw new ArgumentException(" 获取规格服务信息失败,请检查数据 ");
            }
            entity.Price = price;
            entity.UpdateTime = DateTime.Now;
            entity.EditAdminId = admin.AdminId;
            entity.EditAdminName = admin.FullName;
            var result = moveHouseSpecificationServiceConfigData.UpdateAysnc(entity).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
            return result != null;
        }

        public bool Enabled(long moveHouseSpecificationServiceConfigId, AdminDto admin)
        {
            if (admin.CompanyId != 1)
            {
                throw new ArgumentException(" 用户认证失败,错误操作 ");
            }
            var entity = moveHouseSpecificationServiceConfigData.GetSingle(moveHouseSpecificationServiceConfigId).Result;
            if (entity == null)
            {
                throw new ArgumentException(" 获取规格服务信息失败,请检查数据 ");
            }
            var specificationConfigEntity = moveHouseSpecificationConfigData.GetSingle(entity.MoveHouseSpecificationConfigId).Result;
            if (!specificationConfigEntity.Enabled)
            {
                throw new ArgumentException(" 当前服务的规格被禁用,不可启用 ");
            }
            entity.Enabled = true;
            entity.UpdateTime = DateTime.Now;
            entity.EditAdminId = admin.AdminId;
            entity.EditAdminName = admin.FullName;
            var result = moveHouseSpecificationServiceConfigData.UpdateAysnc(entity).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
            return result != null;
        }

        public bool Disabled(long moveHouseSpecificationServiceConfigId, AdminDto admin)
        {
            if (admin.CompanyId != 1)
            {
                throw new ArgumentException(" 用户认证失败,错误操作 ");
            }
            var entity = moveHouseSpecificationServiceConfigData.GetSingle(moveHouseSpecificationServiceConfigId).Result;
            if (entity == null)
            {
                throw new ArgumentException(" 获取规格服务信息失败,请检查数据 ");
            }
            var overWrite = moveHouseSpecificationServiceConfigOverWriteData.GetEntityByConfigId(moveHouseSpecificationServiceConfigId).Result;
            if (overWrite != null)
            {
                throw new ArgumentException(" 当前规格服务已被代理商重写,不可禁用 ");
            }
            entity.Enabled = false;
            entity.UpdateTime = DateTime.Now;
            entity.EditAdminId = admin.AdminId;
            entity.EditAdminName = admin.FullName;
            var result = moveHouseSpecificationServiceConfigData.UpdateAysnc(entity).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
            return result != null;
        }

        public IEnumerable<MoveHouseSpecificationServiceConfigViewDto> GetAllServiceQuery(AdminDto admin)
        {
            string cacheKey = this.redisService.GetKey(keyView);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var list = moveHouseSpecificationServiceConfigData.GetList().Result.As<IEnumerable<MoveHouseSpecificationServiceConfigViewDto>>();
                return list;
            }, TimeSpan.FromDays(1));
            return result;
        }
    }
}
